# pylint: disable=R0201
import logging
from flask import request
from flask_restx import Resource
from patch_tracking.api.serializers import tracking
from patch_tracking.api.parsers import tracking_request
from patch_tracking.api.restplus import api
from patch_tracking.database.models import Tracking
from patch_tracking.api.business import create_tracking, update_tracking

log = logging.getLogger(__name__)

ns = api.namespace('tracking', description='Operations related to tracking')


@ns.route('')
class TrackingCollection(Resource):
    @api.expect(tracking_request)
    @api.marshal_list_with(tracking)
    def get(self):
        """
        Returns list of tracking
        """
        trackings = Tracking.query.all()
        return trackings

    @api.expect(tracking)
    @api.response(201, 'Tracking successfully created.')
    @api.response(204, 'Tracking successfully updated.')
    def post(self):
        """
        Creates os update a tracking.
        """
        data = Tracking.query.filter_by(repo=request.json['repo'], branch=request.json['branch']).first()
        if data:
            update_tracking(request.json)
            return None, 204

        create_tracking(request.json)
        return None, 201
